<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Admin\Controller;

use Admin\Api\DatatreeApi;
use Admin\Api\OrgMemberApi;
use Admin\Model\MessageModel;
use Common\Api\ExchangeLogApi;
use Shop\Api\AlipayNotifyApi;
use Shop\Api\OrdersContactInfoApi;
use Shop\Api\ProductFaqApi;
use Shop\Api\WxpayNotifyApi;
use Shop\Api\OrderRefundMoneyApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrderCommentApi;
use Shop\Api\OrderCommentAttachsApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\OrdersInfoViewApi;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrderStatusApi;
use Shop\Api\OrderStatusHistoryApi;
use Shop\Model\OrdersModel;
use Shop\Api\OrderRefundApi;
use Think\Hook;
use Api\Controller\WxpayAppController;
use Tool\Api\CityApi;
use Tool\Api\ProvinceApi;
use Uclient\Api\UserApi;


class OrdersController extends AdminController {
	/**
	 * 初始化
	 */
	protected function _initialize() {
		parent::_initialize();
	}

  /**
   * 订单上报
   */
  public function upload(){
        $map['pay_status'] = OrdersModel::ORDER_PAID;
        $map['order_status'] = OrdersModel::ORDER_SHIPPED;
        $params = array();
        if (!empty($order_code)) {
            $map['order_code'] =$order_code;
            $params['order_code'] = $order_code;
            $this->assign("order_code",$order_code);
        }

        $page = array('curpage' => I('get.p', 0), 'size' => C('LIST_ROWS'));
        $order = " createtime asc ";


        $result = apiCall(OrdersInfoViewApi::QUERY, array($map, $page, $order, $params));
        if(!$result['status']){
            $this->error($result['info']);
        }

        $this -> assign('list', $result['info']['list']);
        $this -> assign('show', $result['info']['show']);
        $this->display();

  }

	/**
	 * 商家主动退回订单
	 */
	public function backOrder(){
		$id = I('post.orderid',0);
		$reason = I('post.reason','商家主动取消订单');

		$result = apiCall(OrdersApi::GET_INFO, array(array('id'=>$id)));

		if(!$result['status']){
			$this->error($result['status']);
		}

		if(is_null($result)){
			$this->error("订单信息获取失败，请重试！");
		}

		$cur_status = $result['info']['order_status'];
        $uid = $result['info']['uid'];

        //检测当前订单状态是否合法
		if($cur_status != 2){
			$this->error("当前订单状态无法变更！");
		}
        $order_code = $result['info']['order_code'];
		//
		$result = apiCall(OrderStatusApi::BACK_ORDER, array($order_code,$reason,false,UID));

		if(!$result['status']){
			$this->error($result['info']);
		}

		//===========推送给用户消息↓
		$text = "您的订单:".$order_code." [被退回],原因:".$reason.". [查看详情]";
		$msg = array(
			'title'=>'订单退回通知',
			'content'=>$text,
			'summary'=>'订单被退回'
		);
		$this->pushOrderMessage($order_code,$msg);
		//===========推送给用户消息↑

        //======================================
		$this->success("退回成功!");

	}

	/**
	 * 统计
	 */
	public function statics(){
		//TODO:可能数据库写一个视图效率更高吧，之后考虑
		//TODO:目前先是全表统计，之后可能考虑按时间，当天，本月，本年计算


		//地区管理员所属地区限制
		$AreaMap = $this->OrgAreaMap();

		/**
		 * 订单退回
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_BACK,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$orderback=apiCall(OrdersInfoViewApi::COUNT,array($map));
		/**
		 * 待确认
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_TOBE_CONFIRMED,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$ordertobeconfirmed=apiCall(OrdersInfoViewApi::COUNT,array($map));
		/**
		 * 待发货
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_TOBE_SHIPPED,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$ordertobeshipped=apiCall(OrdersInfoViewApi::COUNT,array($map));
		/**
		 * 已发货
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_SHIPPED,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$ordershipped=apiCall(OrdersInfoViewApi::COUNT,array($map));
		/**
		 * 已收货
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_RECEIPT_OF_GOODS,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$orderreceiptofgoods=apiCall(OrdersInfoViewApi::COUNT,array($map));
		/**
		 * 已退货
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_RETURNED,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$orderreturned=apiCall(OrdersInfoViewApi::COUNT,array($map));
		/**
		 * 已完成
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_COMPLETED,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$ordercompleted=apiCall(OrdersInfoViewApi::COUNT,array($map));
		/**
		 * 取消或交易关闭
		 */
		$map=array(
			'order_status'=>OrdersModel::ORDER_CANCEL,
		);
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$ordercancel=apiCall(OrdersInfoViewApi::COUNT,array($map));
		//dump($orderback);
		$orderstatus=array(
			'order_back'=>$orderback['info'],
			'order_tobe_confirmed'=>$ordertobeconfirmed['info'],
			'order_tobe_shipped'=>$ordertobeshipped['info'],
			'order_shipped'=>$ordershipped['info'],
			'order_receipt_of_goods'=>$orderreceiptofgoods['info'],
			'order_returned'=>$orderreturned['info'],
			'order_completed'=>$ordercompleted['info'],
			'order_cancel'=>$ordercancel['info']
		);
		$map=array();
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$price=apiCall(OrdersInfoViewApi::SUM,array($map,"price"));

		/**
		 * 商品咨询待回复
		 */
		$map=array(
			'reply_time'=>0,
		);
		$faqtobereply = apiCall(ProductFaqApi::COUNT,array($map));
		/**
		 * 积分商品待发货
		 */
		$map=array(
			'exchange_status'=>0,
		);
		$score_goods_tobe_deliver = apiCall(ExchangeLogApi::COUNT,array($map));

		$this->assign('order_status',$orderstatus);
		$this->assign('price',$price['info']);
		$this->assign('faqtobereply',$faqtobereply['info']);
		$this->assign('score_goods_tobe_deliver',$score_goods_tobe_deliver['info']);
		$this->display();
	}

	/**
	 * 修改订单评价
	 */
	public function comment() {

	}
	/**
	 * 订单管理
	 */
	public function index() {
		$payStatus     = I('paystatus', '');
		$orderStatus   = I('orderstatus', '');
		$commentStatus = I('commentstatus', '');
		$order_code    = I('post.order_code', '');
		$userid        = I('uid', 0);

		$arr           = getDataRange(3);
		$startdatetime = urldecode($arr[0]);
		//I('startdatetime', , 'urldecode');
		$enddatetime   = urldecode($arr[1]);
		//I('enddatetime',   , 'urldecode');
		//分页时带参数get参数
		$params = array('startdatetime' => $startdatetime, 'enddatetime' => ($enddatetime),'wxaccountid'=>getWxAccountID());
		$startdatetime = strtotime($startdatetime);
		$enddatetime   = strtotime($enddatetime);
		if ($startdatetime === FALSE || $enddatetime === FALSE) {
			LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error(L('ERR_DATE_INVALID'));
		}

		$map = array();
		$map['createtime'] = array( array('EGT', $startdatetime), array('elt', $enddatetime), 'and');
		//$map['wxaccountid'] = getWxAccountID();
		if (!empty($order_code)) {
			$map['order_code'] = array('like', $order_code . '%');
		}
		if ($payStatus != '') {
			$map['pay_status']   = $payStatus;
			$params['paystatus'] = $payStatus;
		}
		if ($orderStatus != '') {
			$map['order_status']   = $orderStatus;
			$params['orderstatus'] = $orderStatus;
		}
		if ($commentStatus != '') {
			$map['comment_status']   = $commentStatus;
			$params['commentstatus'] = $commentStatus;
		}

		$page = array('curpage' => I('get.p', 0), 'size' => C('LIST_ROWS'));
		$order = " createtime desc ";

		if ($userid > 0) $map['uid'] = $userid;

		//地区管理员所属地区限制
		$AreaMap = $this->OrgAreaMap();
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$result = apiCall(OrdersInfoViewApi::QUERY, array($map, $page, $order, $params));

		//
		if ($result['status']) {
			$this -> assign('order_code', $order_code);
			$this -> assign('orderStatus', $orderStatus);
			$this -> assign('commentStatus', $commentStatus);
			$this -> assign('payStatus', $payStatus);
			$this -> assign('startdatetime', $startdatetime);
			$this -> assign('enddatetime', $enddatetime);
			$this -> assign('list', $result['info']['list']);
			$this -> assign('show', $result['info']['show']);
			$this -> display();
		} else {
			LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error($result['info']);
		}
	}

	/**
	 * 订单确认
	 */
	public function sure() {
		$order_code = I('param.order_code', '');
		$payStatus = I('payStatus', "");
		$userid = I('uid', 0);
		$params = array();
		$map = array();
		$map['order_status'] = OrdersModel::ORDER_TOBE_CONFIRMED;
		if($payStatus !== ""){
			$map['pay_status'] = $payStatus;
		}

		//$map['wxaccountid']=getWxAccountID();
		$page = array('curpage' => I('get.p', 0), 'size' => C('LIST_ROWS'));
		$order = " createtime desc ";

		if (!empty($order_code)) {
			$map['order_code'] = array('like', $order_code . '%');
			$params['order_code'] = $order_code;
		}
		if ($userid > 0) {
			$map['uid'] = $userid;
			$params['uid'] = $userid;
		}

		//地区管理员所属地区限制
		$AreaMap = $this->OrgAreaMap();
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$result = apiCall(OrdersInfoViewApi::QUERY, array($map, $page, $order, $params));

		//
		if ($result['status']) {

			$this -> assign('order_code', $order_code);
			$this -> assign('payStatus', $payStatus);
			//$this -> assign('orderStatus', $orderStatus);
			$this -> assign('show', $result['info']['show']);
			$this -> assign('list', $result['info']['list']);
			$this -> display();
		} else {
			LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error($result['info']);
		}
	}

	/**
	 * 发货
	 */
	public function deliverGoods() {
		$orderStatus = I('orderstatus','3');
		$ordercode = I('order_code', '');
		$userid = I('uid', 0);
		$params = array();

		$map = array();
		//$map['wxaccountid']=getWxAccountID();
		//$params['uid'] = $map['uid'];
		if (!empty($ordercode)) {
			$map['order_code'] = array('like', $ordercode . '%');
			$params['order_code'] = $ordercode;
		}


		if($orderStatus != ''){
			$map['order_status'] = $orderStatus;
			$params['order_status'] = $orderStatus;
		}

		$map['pay_status']=array(
			'in',array(OrdersModel::ORDER_CASH_ON_DELIVERY,OrdersModel::ORDER_PAID)
		);
		$page = array('curpage' => I('get.p', 0), 'size' => C('LIST_ROWS'));
		$order = " createtime desc ";

		if ($userid > 0) {
			$map['u'] = $userid;
		}

		//地区管理员所属地区限制
		$AreaMap = $this->OrgAreaMap();
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$result = apiCall(OrdersInfoViewApi::QUERY, array($map, $page, $order, $params));

		//
		if ($result['status']) {
			$this -> assign('order_code', $ordercode);
			$this -> assign('orderStatus', $orderStatus);
			$this -> assign('show', $result['info']['show']);
			$this -> assign('list', $result['info']['list']);
			$this -> display();
		} else {
			LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error($result['info']);
		}
	}

	/**
	 * 查看
	 */
	public function view() {
		if (IS_GET) {
			$id = I('get.id',0);
			$map = array('id'=>$id);
			$result = apiCall(OrdersInfoViewApi::GET_INFO, array($map));
			if ($result['status']) {
				// dump($result['info']);
				$order_code = $result['info']['order_code'];
				$comment_status = $result['info']['comment_status'];
				$this -> assign("order", $result['info']);
				$result = apiCall(OrdersItemApi::QUERY_NO_PAGING, array(array('order_code'=>$order_code)));
				if(!$result['status']){
					ifFailedLogRecord($result, __FILE__.__LINE__);
					$this->error($result['info']);
				}
				// dump($result['info']);exit;
				$items = $result['info'];
				if($comment_status != OrdersModel::ORDER_TOBE_EVALUATE){
					foreach ($items	as &$v) {
						//已评价订单
						//商品评价详情
						$result = apiCall(OrderCommentApi::GET_INFO,array(array('order_code'=>$v['order_code'],'product_id'=>$v['p_id'])));
						if(!$result['status']){
							ifFailedLogRecord($result, __FILE__.__LINE__);
							$this->error($result['info']);
						}
						$this->getAttachs($result['info']['id'],10,$result['info']);
						$v['comment_info'] = $result['info'];
					}
				}
				// dump($items);exit;
				$this -> assign("items", $items);

				//查询订单状态变更纪录
				$result = apiCall(OrderStatusHistoryApi::QUERY_NO_PAGING, array(array('order_code'=>$order_code),"create_time desc"));
//				dump($result);
				if(!$result['status']){
					ifFailedLogRecord($result, __FILE__.__LINE__);
					$this->error($result['info']);
				}

				$this -> assign("statushistory", $result['info']);
				$this -> display();
			} else {
				$this -> error($result['info']);
			}
		}
	}

	/**
	 * 单个发货操作
	 */
	public function deliver() {
		$result = apiCall(DatatreeApi::QUERY_NO_PAGING,array(array('parentid'=>6003)));
		$expresslist = array();
		if($result['status']){
			foreach($result['info'] as $val){
				$expresslist[$val['code']] = $val['name'];
			}
		}else{
			$this->error("物流公司列表获取失败！");
		}
		//$expresslist = C("CFG_EXPRESS");
        //$support_express = "ems,";
		if (IS_GET) {
			$id = I('get.id',0);
			$map = array('id'=>$id);
			$result = apiCall(OrdersInfoViewApi::GET_INFO, array($map));
			if($result['status']){
				$this->assign("order",$result['info']);
			}else{
				$this->error("订单信息获取失败！");
			}
			//dump($result);
			$map = array('order_code'=>$result['info']['order_code']);
			$result = apiCall(OrdersExpressApi::GET_INFO, array($map));
			//dump($result);
			if($result['status'] && is_array($result['info'])){
				$this->assign("express",$result['info']);
			}
			$this->assign("expresslist",$expresslist);
			$this->display();
		} elseif (IS_POST) {

			$expresscode = I('post.expresscode','');
			$expressno = I('post.expressno','');
			$uid = I('post.uid',0);
			$ordercode = I('post.ordercode','');
			$orderOfid = I('post.orderOfid','');
			if(empty($expresscode) || !isset($expresslist[$expresscode])){
				$this->error("快递信息错误！");
			}
			if(empty($expressno)){
				$this->error("快递单号不能为空");
			}
			$id = I('post.id',0);
			$entity = array(
				  'expresscode'=>$expresscode,
				  'expressname'=>$expresslist[$expresscode],
				  'expressno'=>$expressno,
				  'note'=>I('post.note',''),
				  'order_code'=>$ordercode,
				  'uid'=>$uid,
			);

			if(empty($entity['order_code'])){
				$this->error("订单编号不能为空");
			}
			$deliver = false;
			if(empty($id) || $id <= 0){
				$result = apiCall(OrdersExpressApi::ADD, array($entity));
			}else{
				$result = apiCall(OrdersExpressApi::SAVE_BY_ID, array($id,$entity));
				$deliver = true;
			}


			if($result['status']){

				// 1. 修改订单状态为已发货
                $result = apiCall(OrderStatusApi::SHIPPED, array($ordercode,false,UID));

                if(!$result['status']){
					ifFailedLogRecord($result['info'], __FILE__.__LINE__);
				}

                //========================================
				if($deliver) {
					$text = "亲，您的订单($ordercode)已发货，快递单号：$expressno,快递公司：".$expresslist[$expresscode].",请注意查收";
					$summary = '订单已发货';
				}
				else{
					$text = "亲，您的订单($ordercode)物流信息已改变，快递单号：$expressno,快递公司：".$expresslist[$expresscode].",请注意查收";
					$summary = '物流信息已改变';
				}


				// 2.发送提醒信息给指定用户
				//===========推送给用户消息↓
				$msg = array(
					'title'=>'物流通知',
					'content'=>$text,
					'summary'=>$summary
				);
				$this->pushOrderMessage($ordercode,$msg);
                //========================================

				$this->success(L('RESULT_SUCCESS'),U('Admin/Orders/deliverGoods'));
			}else{
				$this->error($result['info']);
			}
		}
	}

	/**
	 * 售后管理
	 */
	public function afterSale(){
		$order_code = I('order_code', '');
		$userid = I('uid', 0);
		$valid_status=I('valid_status',0);

		$params = array();
		$map = array();
		if (!empty($order_code)) {
			$map['order_code'] = array('like', $order_code . '%');
			$params['order_code'] = $order_code;
		}
		$params['valid_status'] = $valid_status;
		//$map['wxaccountid'] = getWxAccountID();
		if(isset($orderStatus)){
			$map['order_status'] = $orderStatus;
			//$params['order_status'] = $orderStatus;
		}

		$map['pay_status'] = OrdersModel::ORDER_PAID;


		$page = array('curpage' => I('get.p', 0), 'size' => C('LIST_ROWS'));
		$order = " create_time desc ";

		if ($userid > 0) {
			$map['uid'] = $userid;
		}

		$map['valid_status'] = $valid_status;

		//地区管理员所属地区限制
		$AreaMap = $this->OrgAreaMap();
		if(!empty($AreaMap)) $map['_complex'] = $AreaMap;
		$result = apiCall(OrderRefundApi::QUERY_WITH_ORDER,array($map, $page, $order, $params));
		//
		if ($result['status']) {
			$this -> assign('order_code', $order_code);
			$this -> assign('orderStatus', $orderStatus);
			$this -> assign('valid_status', $valid_status);
			$this -> assign('show', $result['info']['show']);
			$this -> assign('list', $result['info']['list']);
			$this -> display();
		} else {
			LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
			$this -> error($result['info']);
		}

	}


	/**
	 * 退货管理
	 */
	public function returned() {
		//		if (IS_GET) {
            $order_code = I('order_code', '');
			$userid = I('uid', 0);
			$valid_status=I('valid_status',0);
			if($valid_status==1){
				$orderStatus = I('orderstatus', OrdersModel::ORDER_RETURNED);
			}else {
				$orderStatus = I('orderstatus', OrdersModel::ORDER_RECEIPT_OF_GOODS);
			}
			$params = array();
			$map = array();
			if (!empty($order_code)) {
				$map['order_code'] = array('like', $order_code . '%');
				$params['order_code'] = $order_code;
			}
			//$map['wxaccountid'] = getWxAccountID();
			$map['order_status'] = $orderStatus;
			$map['pay_status'] = OrdersModel::ORDER_PAID;

			$params['order_status'] = $orderStatus;
			$page = array('curpage' => I('get.p', 0), 'size' => C('LIST_ROWS'));
			$order = " createtime desc ";

			if ($userid > 0) {
				$map['uid'] = $userid;
			}

			//
			$result = apiCall(OrdersInfoViewApi::QUERY, array($map, $page, $order, $params));

			$map=array(
				'valid_status'=>$valid_status
			);

			$tui=apiCall(OrderRefundApi::QUERY,array($map));
			$this->assign('ths',$tui['info']['list']);
			//
			if ($result['status']) {

				$this -> assign('order_code', $order_code);
				$this -> assign('orderStatus', $orderStatus);
				$this -> assign('valid_status', $valid_status);
				$this -> assign('show', $tui['info']['show']);
				$this -> assign('list', $result['info']['list']);
				$this -> display();
			} else {
				LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
				$this -> error($result['info']);
			}
//		} elseif (IS_POST) {
//
//		}
	}

	public function close(){
		$thid=I('thid',0);
		$order_code = '';
		$result = apiCall(OrderRefundApi::GET_INFO,array(array('id'=>$thid)));

		if($result['status']){
			if(is_null($result['info'])){
				$this->error('指定售后记录不存在');
			}else{
				$order_code = $result['info']['order_code'];

			}
		}else{
			$this->error('操作失败');
		}

		$result = apiCall(OrderStatusApi::CLOSE,array($order_code,false,UID));

		if($result['status']){

			//===========推送给用户消息↓
			$text = "亲，您订单($order_code)已被关闭";
			$msg = array(
					'title'=>'关闭订单通知',
					'content'=>$text,
					'summary'=>'订单已关闭'
			);
			$this->pushOrderMessage($order_code,$msg);
			//===========推送给用户消息↑

			$this -> success("交易已关闭");
		}else{
			$this -> error($result['info']);
		}

	}

	/**
	 * 单个申请退货操作
	 */
	public function returnGoods(){
		if(IS_GET){
			$id = I('get.id',0);
			$thid = I('get.thid',0);
			$this->assign("thid",$thid);
			$this->assign("id",$id);
			$this->display();
		}else{
			$id = I('id',0);
			$thid=I('thid',0);
			$order_code = '';
			$result = apiCall(OrderRefundApi::GET_INFO,array(array('id'=>$thid)));

			if($result['status']){
				if(is_null($result['info'])){
					$this->error('指定售后记录不存在');
				}else{
					$order_code = $result['info']['order_code'];

				}
			}else{
				$this->error('操作失败');
			}

			$entity=array(
                'valid_status'=>1,
                'reply_msg'=>I('note','无'),
                'order_code'=>$order_code,
            );

            $result = apiCall(OrderStatusApi::RETURNED,array($order_code,0,UID));

			if($result['status']){

				$result = apiCall(OrderRefundApi::SAVE_BY_ID,array($thid,$entity));
				if($result['status']){

					//修改订单售后状态为已通过
					apiCall(OrderRefundApi::CHANGE_SERVICE_STATUS,array($order_code,OrdersModel::CS_PROCESSED));

					//===========推送给用户消息↓
					$text = "亲，您订单($order_code)的退货申请已通过";
					$msg = array(
						'title'=>'退货申请通知',
						'content'=>$text,
						'summary'=>'退货申请已通过'
					);
					$this->pushOrderMessage($order_code,$msg);
					//===========推送给用户消息↑


					$this->success("操作成功！",U('Admin/Orders/afterSale'));
				}else{
					$this->error('操作失败');
				}

			}else{
				$this->error($result['info']);
			}
		}
	}

	public function test(){
		$r = apiCall(WxpayAppController::REFUND,array('WIDbatch_no'=>$batch_no,'WIDdetail_data'=>$data));
		dump($r);exit;
	}
	/**
	 * 单个申请退款操作
	 */
	public function refund(){
		if(IS_GET){
			$id = I('get.id',0);
			$thid = I('get.thid',0);
			$this->assign("thid",$thid);
			$this->assign("id",$id);
			$this->display();
		}else{
			$id = I('id',0);
			$thid=I('thid',0);
			$money=I('money',0);
			if(!is_numeric($money)){
				$this->error('退款金额必须为数字');
			}
			$order_code = '';
			$result = apiCall(OrderRefundApi::GET_INFO,array(array('id'=>$thid)));

			if($result['status']){
				if(is_null($result['info'])){
					$this->error('指定售后记录不存在');
				}else{
					$Refund_info = $result['info'];
					$order_code = $Refund_info['order_code'];

				}
			}else{
				$this->error('操作失败');
			}

			$entity=array(
				'valid_status'=>1,
				'reply_msg'=>I('note','无'),
				'order_code'=>$order_code,
			);

			$result = apiCall(OrderRefundApi::SAVE_BY_ID,array($thid,$entity));
			if(!$result['status']){

				$this->error('操作失败');
			}

			//1.写退款记录
			$batch_no = date('Ymd').$Refund_info['id'].time();
			//查找交易号

			$result = apiCall(OrdersApi::GET_INFO,array(array('order_code'=>$order_code)));
			if($result['status']){
				$pay_code = $result['info']['pay_code'];
			}else{
				$this->error('交易号查询失败');
			}
			if(empty($pay_code)){
				$this->error('没有该交易记录');
			}
			//edit begin by zhouzhou
			$type = intval($result['info']['pay_type']);
			// echo '--'.$type.'--';
			if($type === 1){
				//支付宝
				$result = apiCall(AlipayNotifyApi::GET_INFO,array(array('out_trade_no'=>$pay_code)));
				$url = 'Api/AlipayRefund/submit';
			}elseif($type === 2){
				//微信
				$url = 'Api/WxpayApp/refundSubmit';
				$result = apiCall(WxpayNotifyApi::GET_INFO,array(array('out_trade_no'=>$pay_code)));
			}else{
				$this->error('未知交易类型');
			}
			if($result['status']){
				$trade_no = $result['info']['trade_no'];
			}else{
				$this->error('交易号查询失败');
			}
			if(empty($pay_code)){
				$this->error('没有该交易记录');
			}
			$data = $trade_no.'^'.$money.'^'.'协商退款';
			$entity = array(
				'order_code' => $order_code,
				'reason' => $Refund_info['reason'],
				'result' => 0,
				'result_data' => '',
				'data' => $data,
				'money' => $money,
				'currency' => 'RMB',
				'refund_channel' => $type,
				'batch_no' => $batch_no,
			);
			$result = apiCall(OrderRefundMoneyApi::SAVE,array(array('order_code'=>$order_code),$entity));
			if($result['status']){

				//修改订单售后状态为已通过
				apiCall(OrderRefundApi::CHANGE_SERVICE_STATUS,array($order_code,OrdersModel::CS_PROCESSED));

				//===========推送给用户消息↓
				$text = "亲，您订单($order_code)的退款申请已通过，将退还给您$money 元，请注意查收";
				$msg = array(
					'title'=>'退款申请通知',
					'content'=>$text,
					'summary'=>'退款申请已通过'
				);
				$this->pushOrderMessage($order_code,$msg);
				//===========推送给用户消息↑
				if($result['info']>0){
				$this->success("操作成功！",U($url,array('WIDbatch_no'=>$batch_no,'WIDdetail_data'=>$data)));
				}
				// if($result['info']>0 && $type === 1){
				// 	$this->success("操作成功！",U($url,array('WIDbatch_no'=>$batch_no,'WIDdetail_data'=>$data)));
				// }elseif($result['info']>0 && $type === 2){
				// 	$r = apiCall(WxpayAppController::REFUND,array('WIDbatch_no'=>$batch_no,'WIDdetail_data'=>$data));
				// 	dump($r);exit;
				// 	// if(!$r['status']) $this->error('系统错误 ：WxpayAppController ：REFUND : ERROR ');
				// 	// $this->success($r['info']);
				// }
				$result = apiCall(OrderRefundMoneyApi::ADD,array($entity));
				if($result['status']){
				$this->success("操作成功！",U($url,array('WIDbatch_no'=>$batch_no,'WIDdetail_data'=>$data)));
					// if($type === 1){
					// 	$this->success("操作成功！",U($url,array('WIDbatch_no'=>$batch_no,'WIDdetail_data'=>$data)));
					// }elseif($type === 2){
					// 	$r = apiCall(WxpayAppController::REFUND,array('WIDbatch_no'=>$batch_no,'WIDdetail_data'=>$data));
					// 	dump($r);exit;
					// 	// if(!$r['status']) $this->error('系统错误 ：WxpayAppController ：REFUND : ERROR ');
					// 	// $this->success($r['info']);
					// }
					//edit end
				}else{
					$this->error($result['info']);
				}
			}else{
				$this->error($result['info']);
			}
		}

	}

	/*
	 * 修改订单信息
	 * */
	public function editorder(){
		if(IS_GET){
			$id = I('get.id',0);
			$price = I('get.price',0);
			$post_price = I('postprice','0.00');
			$this->assign("id",$id);
			$this->assign("price",$price);
			$this->assign('post_price',$post_price);

			//查询地址
			$result = apiCall(OrdersInfoViewApi::GET_INFO,array(array('id'=>$id)));

			if($result['status']){
				$this->assign('contactinfo',$result['info']);
			}

			$this->display();
		}else{
			$id = I('id',0);
			$price = I('post.price',0);
			$post_price = I('post.postprice','0.00');
			$entity=array('price'=>$price,'post_price'=>$post_price);
			$resu=apiCall(OrdersApi::SAVE_BY_ID,array($id,$entity));

			$result = apiCall(OrdersApi::GET_INFO,array(array('id'=>$id)));
			$order_code = $result['info']['order_code'];

			//保存邮寄地址
			$entity = array(
				'contactname'=>I('post.contactname',''),
				'province'=>I('post.province',''),
				'city'=>I('post.city',''),
				'area'=>I('post.area',''),
				'mobile'=>I('mobile',''),
				'postal_code'=>I('post.code',''),
				'detailinfo'=>I('post.detailinfo',''),
			);

			$result = apiCall(OrdersContactInfoApi::SAVE,array(array('order_code'=>$order_code),$entity));
			if(!$result['status']){
				$this->error($result['info']);
			}

			if($resu['status']){

				//===========推送给用户消息↓
				$result = apiCall(OrdersApi::GET_INFO,array(array('id'=>$id)));
				if($result['status']){
					$order_code = $result['info']['order_code'];
					$contactinfo = "邮寄地址：".$entity['province'].$entity['city'].$entity['area']."，联系人：".$entity['contactname']."，联系电话：".$entity['mobile'];
					$text = "亲，您订单($order_code)的订单信息已被修改，订单金额:$price 元，运费:$post_price 元，$contactinfo";
					$msg = array(
						'title'=>'订单信息修改通知',
						'content'=>$text,
						'summary'=>'订单信息被修改'
					);
					$this->pushOrderMessage($order_code,$msg);
					//===========推送给用户消息↑
				}

				//$this->success("操作成功！",U('Admin/Orders/sure'));
			}else{
				$this->error($result['info']);
			}
		}
	}
	/**
	 * 驳回退货申请
	 */
	public function returnGoodsbh(){
		if(IS_GET){
			$id = I('get.id',0);
			$thid = I('get.thid',0);
			$this->assign("thid",$thid);
			$this->assign("id",$id);
			$this->display();
		}else{
			$id = I('id',0);
			$thid=I('thid',0);
			$entity=array('valid_status'=>2,'reply_msg'=>I('note','无'));
			$resu=apiCall(OrderRefundApi::SAVE_BY_ID,array($thid,$entity));
			if($resu['status']){

				//===========推送给用户消息↓
				$result = apiCall(OrderRefundApi::GET_INFO,array(array('id'=>$thid)));
				$refund_info = $result['info'];
				$order_code = $refund_info['order_code'];
				$reply_msg = $refund_info['reply_msg'];
				$text = "亲，您订单($order_code)的退货申请已经被驳回，理由：$reply_msg";
				$msg = array(
					'title'=>'退货申请通知',
					'content'=>$text,
					'summary'=>'退货申请被驳回'
				);
				$this->pushOrderMessage($order_code,$msg);
				//===========推送给用户消息↑


				$this->success("操作成功！",U('Admin/Orders/returned'));
			}else{
				$this->error($result['info']);
			}
		}
	}

	/**
	 * 驳回售后申请
	 */
	public function afterSalebh(){
		if(IS_GET){
			$id = I('get.id',0);
			$thid = I('get.thid',0);
			$this->assign("thid",$thid);
			$this->assign("id",$id);
			$this->display();
		}else{
			$id = I('id',0);
			$thid=I('thid',0);
			$result = apiCall(OrderRefundApi::GET_INFO,array(array('id'=>$thid)));
			$entity=array('valid_status'=>2,'reply_msg'=>I('note','无'));
			$resu=apiCall(OrderRefundApi::SAVE_BY_ID,array($thid,$entity));
			if($resu['status']){

				//===========推送给用户消息↓
				$result = apiCall(OrderRefundApi::GET_INFO,array(array('id'=>$thid)));
				$refund_info = $result['info'];
				$order_code = $refund_info['order_code'];
				$reply_msg = $refund_info['reply_msg'];
				$text = "亲，您订单($order_code)的售后申请已经被驳回，理由：$reply_msg";
				$msg = array(
					'title'=>'售后申请通知',
					'content'=>$text,
					'summary'=>'售后申请被驳回'
				);
				$this->pushOrderMessage($order_code,$msg);
				//===========推送给用户消息↑


				$this->success("操作成功！",U('Admin/Orders/afterSale'));
			}else{
				$this->error($result['info']);
			}
		}
	}

	public function verify(){

		if(IS_POST){

			$ver_pass = I('post.ver_pass','');

			if(APP_DEBUG === true){
				//测试模式下不输入密码
				$this -> success(true);
			}
			$result = apiCall(UserApi::GET_INFO,array(UID));
			if($result['status']){
				if($result['info']['password'] == itboye_ucenter_md5($ver_pass,UC_PASSWORD_SALT)){
					$this -> success(true);
				}else{
					$this -> error('用户名或密码错误');
				}
			}else{
				$this -> error($result['info']);
			}
		}

	}


	/**
	 * 批量发货
	 * TODO:批量发货
	 */
	public function bulkDeliver(){
		$this->error("功能开发中...");
	}

	/**
	 * 批量确认订单
	 */
	public function bulkSure() {
		if (IS_POST) {

			$order_codes = I('post.order_codes', -1);
			if ($order_codes === -1) {
				$this -> error(L('ERR_PARAMETERS'));
			}


			foreach($order_codes as $code){
				$result = apiCall(OrderStatusApi::CONFIRM_ORDER, array($code , false , UID));
				if (!$result['status']) {
					$this -> error($result['info']);
				}else{

					//===========推送给用户消息↓
					$text = "亲，您的订单已被确认,请等待发货，订单号($code)";
					$msg = array(
						'title'=>'订单通知',
						'content'=>$text,
						'summary'=>'订单已确认'
					);
					$this->pushOrderMessage($code,$msg);
					//===========推送给用户消息↑

				}
			}


			$this -> success(L('RESULT_SUCCESS'), U('Admin/Orders/sure'));

		}
	}


	private function sendTextTo($uid,$content){

		Hook::listen("");

	}

	/**
	 * 获取评论附件
	 * @param  int   $cid  评论ID
	 * @return [type]      [description]
	 */
	private function getAttachs($cid,$img=3,&$arr){
		$map = ['comment_id'=>$cid];
		$result = apiCall(OrderCommentAttachsApi::QUERY_NO_PAGING,[$map,false,['pic_id']]);
		if($result['status']){
			$arr['img'] = [];
			foreach($result['info'] as $key=>$v){
				if($key >$img) break;
				array_push($arr['img'],$v['pic_id']);
			}
		}
  }
	/**
	 * 消息推送
	 */
	private function pushMessage($msg_type,$message=array('title'=>' ','content'=>' ','summary'=>' ','extra'=>''),$uid=0,$pushAll=false){
		$result = apiCall('Admin/Message/pushMessageAndRecordWithType',array($msg_type,$message,$uid,$pushAll));
		return $result['status'];
	}

	/**
 	* 推送订单消息
 	*/
	private function pushOrderMessage($order_code,$msg=array('title'=>'订单通知','content'=>'订单通知内容','summary'=>'订单通知摘要')){
		//推送订单确认消息
		$result = apiCall(OrdersApi::GET_INFO,array(array('order_code'=>$order_code)));
		if($result['status'] && !is_null($result['info'])){
			$uid= $result['info']['uid'];

			$result = apiCall(OrdersItemApi::GET_INFO,array(array('order_code'=>$order_code)));
			if($result['status']){
				$img = $result['info']['img'];
			}
			$extra = json_encode(array('order_code'=>$order_code,'img'=>$img));
			$result = $this->pushMessage(MessageModel::MESSAGE_ORDER,$message=array('title'=>$msg['title'],'content'=>$msg['content'],'summary'=>$msg['summary'],'extra'=>$extra),$uid);
		}
	}

	/**
	 * 地区管理员地区集map
	 */
	private function OrgAreaMap(){

		$permisson = R('OrgArea/check_manager_permisson',array(),'Widget');
		$this->assign('permisson',$permisson);
		$AreaMap = array();

		if($permisson != 7) return $AreaMap;//不是地区管理员

		$cityid = array();
		$map['type'] = 1;
		$map['member_uid'] = UID;
		$result = apiCall(OrgMemberApi::QUERY_NO_PAGING,array($map));
		if($result['status']){
			foreach($result['info'] as $val){
				array_push($cityid,$val['organization_id']);
			}

		}

		$provinceid = array();
		$map['type'] = 0;
		$result = apiCall(OrgMemberApi::QUERY_NO_PAGING,array($map));
		if($result['status']){
			foreach($result['info'] as $val){
				array_push($provinceid,$val['organization_id']);
			}

		}
		$cityid = implode(',',$cityid);
		$provinceid = implode(',',$provinceid);


		$city = array(-1);
		$province = array(-1);
		//查询地区名称
		if(!empty($cityid)){
			$map = "cityid in($cityid)";
			$filed = 'city';
			$result = apiCall(CityApi::QUERY_NO_PAGING,array($map,false,$filed));
			if($result['status']) $city = array_column($result['info'],'city');
		}


		if(!empty($provinceid)){
			$map = "provinceid in($provinceid)";
			$filed = 'province';
			$result = apiCall(ProvinceApi::QUERY_NO_PAGING,array($map,false,$filed));
			if($result['status']) $province = array_column($result['info'],'province');
		}


		$AreaMap = array(
			'city' => array('in',$city),
			'province' => array('in',$province),
			'_logic' => 'or'
		);

		return $AreaMap;

	}


}
